package com.yd.mvc.baseController.util;


import com.yd.app.util.BusinessException;
import com.yd.app.util.SystemException;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理器
 */
public class ExceptionHandler implements HandlerExceptionResolver,Ordered {

	private MappingJackson2JsonView jsonView=new MappingJackson2JsonView();
	private ExceptionHandlerCallback errorCallBack;

	private String errorMsg="系统繁忙，请稍后重试！";


	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		//根据请求头判断是否为ajax请求 angularjs的resource服务请求貌似不带该请求头 所以这里暂时放弃这种方式的使用
		//boolean isAjax="XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
		ModelAndView mav = new ModelAndView();
		response.setStatus(200);
		mav.getModelMap().put("status",0);
		if (ex instanceof BusinessException) {
				mav.getModelMap().put("type", ((BusinessException) ex).getType());
				mav.getModelMap().put("message", ex.getMessage());
			//response.setStatus(0);
		}else if(ex instanceof SystemException) {
				mav.getModelMap().put("type", "error-system");
				mav.getModelMap().put("message", ex.getMessage());
		} else {
				mav.getModelMap().put("type", "error");
				mav.getModelMap().put("message", errorMsg);
		}
		ex.printStackTrace();
		mav.setView(jsonView);
		//如果有回调 则调用回调
		if(errorCallBack!=null){
			errorCallBack.callback(request,response,handler,ex);
		}
		return mav;
	}
	public ExceptionHandlerCallback getErrorCallBack() {
		return errorCallBack;
	}

	public void setErrorCallBack(ExceptionHandlerCallback errorCallBack) {
		this.errorCallBack = errorCallBack;
	}
	@Override
	public int getOrder() {
		return 1;
	}
}
